1. 题目描述(简单难度)

[success] 606. 根据二叉树创建字符串

2. 解法一:DFS

class Solution {
    public String tree2str(TreeNode root) {
       if(root == null){
           return null;
       }
       StringBuilder sb = new StringBuilder();
       preOrder(root,sb);
       return sb.toString();
    }

    public void preOrder(TreeNode root,StringBuilder sb){
        if(root == null){
            return;
        }
        sb.append(root.val);
        if(root.left != null || root.right != null){
            sb.append("(");
            preOrder(root.left,sb);
            sb.append(")");
            if(root.right != null){
                sb.append("(");
                preOrder(root.right,sb);
                sb.append(")");
            }
        }
    }
}
© gaohueric all right reserved,powered by Gitbook文件修订时间: 2021-12-08 23:22:22

results matching ""

    No results matching ""